package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.entity.*;
import com.chixing.VO.OrderQueryVO;
import com.chixing.mapper.*;
import com.chixing.service.IOrderDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单详情服务实现类
 * </p>
 *
 * @author smith
 * @since 2025-10-01
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {

    @Override
    public List<OrderDetail> getAllOrderDetails() {
        return baseMapper.selectList(null);
    }

    @Override
    public OrderDetail getOrderDetailById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean saveOrderDetail(OrderDetail orderDetail) {
        return save(orderDetail);
    }

    @Override
    public boolean updateOrderDetail(OrderDetail orderDetail) {
        return updateById(orderDetail);
    }

    @Override
    public boolean removeOrderDetailById(Integer id) {
        return removeById(id);
    }

    @Override
    public List<OrderDetail> getDetailsByOrderId(Integer orderId) {
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return baseMapper.selectList(queryWrapper);
    }

    @Autowired
    private OrderBaseMapper orderBaseMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private CinemaMapper cinemaMapper;

    @Autowired
    private HallMapper hallMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;

    @Override
    public List<OrderQueryVO> getOrdersByUserId(Integer userId) {

        return getOrdersByUserIdAndStatus(userId, null);
    }

    // 按用户ID和状态查询订单
    @Override
    public List<OrderQueryVO> getOrdersByUserIdAndStatus(Integer userId, Integer status) {
        // 1. 构建查询条件（用户ID+状态）
        QueryWrapper<OrderBase> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("user_id", userId);
        // 如果状态不为null，添加状态筛选条件
        if (status != null) {
            orderWrapper.eq("status", status); // 假设订单状态字段名为status
        }
        // 按下单时间倒序（最新的订单在前）
        orderWrapper.orderByDesc("order_time");

        List<OrderBase> orderBases = orderBaseMapper.selectList(orderWrapper);
        List<OrderQueryVO> resultList = new ArrayList<>();

        // 2. 封装VO对象
        for (OrderBase orderBase : orderBases) {
            OrderQueryVO vo = new OrderQueryVO();
            // 设置订单基础信息（包含状态）
            vo.setOrderNumber(orderBase.getOrderNumber());
            vo.setOrderTime(orderBase.getOrderTime());
            vo.setOriginalPrice(orderBase.getOriginalPrice());
            vo.setTicketCode(orderBase.getTicketCode());
            vo.setFinalPrice(orderBase.getFinalPrice());
            vo.setSeatCoordinates(orderBase.getSeatCoordinates());
            vo.setStatues(orderBase.getStatues());
            vo.setOrderId(orderBase.getOrderId());

            // 3. 关联订单详情
            QueryWrapper<OrderDetail> detailWrapper = new QueryWrapper<>();
            detailWrapper.eq("order_id", orderBase.getOrderId());
            List<OrderDetail> details = orderDetailMapper.selectList(detailWrapper);
            if (!details.isEmpty()) {
                OrderDetail detail = details.get(0);
                vo.setMovieImage(detail.getMovieImage());
                vo.setMovieName(detail.getMovieName());
                vo.setTicketCount(detail.getTicketCount());
            }

            // 4. 关联场次、影院、影厅信息
            Schedule schedule = scheduleMapper.selectById(orderBase.getScheduleId());
            if (schedule != null) {
                vo.setStartTime(schedule.getStartTime().toLocalTime());
                // 影院信息
                Cinema cinema = cinemaMapper.selectById(schedule.getCinemaId());
                if (cinema != null) {
                    vo.setCinemaName(cinema.getCinemaName());
                }
                // 影厅信息
                Hall hall = hallMapper.selectById(schedule.getHallId());
                if (hall != null) {
                    vo.setHallNumber(hall.getHallNumber());
                }
            }
            // 5. 关联优惠券信息
            Integer userCouponId = orderBase.getUserCouponId();
            if (userCouponId != null) {
                UserCoupon userCoupon = userCouponMapper.selectById(userCouponId);
                if (userCoupon != null) {
                    Coupon coupon = couponMapper.selectById(userCoupon.getCouponId());
                    if (coupon != null) {
                        vo.setCouponName(coupon.getCouponName());
                        vo.setCouponValue(coupon.getCouponValue().doubleValue());
                    }
                }
            }

            resultList.add(vo);
        }

        return resultList;
    }
    @Override
    public OrderQueryVO getOrderByNumber(String orderNumber) {
        // 1. 根据订单号查询订单基础信息
        QueryWrapper<OrderBase> orderWrapper = new QueryWrapper<>();
        orderWrapper.eq("order_number", orderNumber);
        OrderBase orderBase = orderBaseMapper.selectOne(orderWrapper);

        if (orderBase == null) {
            return null;
        }

        OrderQueryVO vo = new OrderQueryVO();

        // 2. 设置订单基础信息
        vo.setOrderNumber(orderBase.getOrderNumber());
        vo.setOrderTime(orderBase.getOrderTime());
        vo.setOriginalPrice(orderBase.getOriginalPrice());
        vo.setTicketCode(orderBase.getTicketCode());
        vo.setFinalPrice(orderBase.getFinalPrice());
        vo.setSeatCoordinates(orderBase.getSeatCoordinates());
        vo.setStatues(orderBase.getStatues());

        vo.setOrderId(orderBase.getOrderId());

        // 3. 获取订单详情
        QueryWrapper<OrderDetail> detailWrapper = new QueryWrapper<>();
        detailWrapper.eq("order_id", orderBase.getOrderId());
        List<OrderDetail> details = orderDetailMapper.selectList(detailWrapper);

        if (!details.isEmpty()) {
            OrderDetail detail = details.get(0);
            vo.setMovieImage(detail.getMovieImage());
            vo.setMovieName(detail.getMovieName());
            vo.setTicketCount(detail.getTicketCount());

        }

        // 4. 获取场次信息
        Schedule schedule = scheduleMapper.selectById(orderBase.getScheduleId());
        if (schedule != null) {
            vo.setStartTime(schedule.getStartTime().toLocalTime());

            // 5. 获取影院信息
            Cinema cinema = cinemaMapper.selectById(schedule.getCinemaId());
            if (cinema != null) {
                vo.setCinemaName(cinema.getCinemaName());
            }

            // 6. 获取影厅信息
            Hall hall = hallMapper.selectById(schedule.getHallId());
            if (hall != null) {
                vo.setHallNumber(hall.getHallNumber());
            }
        }
        // 关联优惠券信息
        Integer userCouponId = orderBase.getUserCouponId();
        if (userCouponId != null) {
            UserCoupon userCoupon = userCouponMapper.selectById(userCouponId);
            if (userCoupon != null) {
                Coupon coupon = couponMapper.selectById(userCoupon.getCouponId());
                if (coupon != null) {
                    vo.setCouponName(coupon.getCouponName());
                    vo.setCouponValue(coupon.getCouponValue().doubleValue());
                }
            }
        }

        return vo;
    }

}
